 //
//  LiveVC.m
//  MPTLive
//
//  Created by HouGeng on 16/1/28.
//  Copyright © 2016年 Jeakin. All rights reserved.
//

#import "LiveVC.h"
#import <MPTLoginApp.h>
#import "MPTSingleObject.h"
#import <JLRoutes.h>
#import "MBProgressHUD.h"
#import "MPTTips.h"


@interface LiveVC ()


@property (nonatomic, strong) TPButton *btn1;
@property (nonatomic, strong) TPButton *btn2;


@end


@implementation LiveVC


#pragma mark - ********************** View Lifecycle **********************

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initVariable]; /// 初始化变量
    [self initViews]; /// 初始化界面
    
    [self regNotification]; /// 注册消息
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[TPTabBarManager share] showBottomView:NO animation:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark - ********************** Init All Views **********************

- (void)initVariable
{
    
}

- (void)initViews
{
    [self initNavView]; /// 初始化Nav导航栏
    
    /// 根据界面情况，决定是单独写函数，或直接写Views
    [self initMainViews];
}

- (void)initNavView
{
    /// 创建导航栏
    [self createNavBarViewWithTitle:@"直播"];
    self.superNavBarView.backgroundColor = RGBAColor(254, 222, 9, 1);
    self.superNavBarView.viewBottomLine.hidden = YES;
    /// 创建左侧按钮
    [self createNavRightBtnWithItem:@"取消"
                            target:self
                            action:@selector(btnClickBack:)];
}

- (void)initMainViews
{
    self.view.backgroundColor = RGBAAllColor(0xf1f1f1, 1.0);
    
    self.btn1 = [TPButton getWithFrame:CGRectMake(15,
                                                  TP_NavBar_H + 15,
                                                  screenW - 30,
                                                  (screenW - 30) *466 / 690)];
    
    [self.btn1 setImage:[UIImage imageNamed:@"shenqingquanxian"] forState:UIControlStateNormal];
    [self.btn1 setImage:[UIImage imageNamed:@"shenqingquanxian_Hl"] forState:UIControlStateHighlighted];
    [self.btn1 addTarget:self action:@selector(btnClickShenqing:) forControlEvents:UIControlEventTouchUpInside];
    
    self.btn2 = [TPButton getWithFrame:self.btn1.frame];
    [self.btn2 setImage:[UIImage imageNamed:@"shenqingquanxian_Other"] forState:UIControlStateNormal];
    [self.btn2 setImage:[UIImage imageNamed:@"shenqingquanxian_Other_Hl"] forState:UIControlStateHighlighted];
    [self.btn2 addTarget:self action:@selector(btnClickShenqingOther:) forControlEvents:UIControlEventTouchUpInside];
    
    // 判断一下之前是否申请过
    NSInteger intCoed = [[[NSUserDefaults standardUserDefaults] objectForKey:LiveCode] integerValue];
    
    if(intCoed == 4)///申请过直播权限
    {
        // 之前申请过
        [self.view addSubview:self.btn2];
    }
    else if (intCoed == 3 || intCoed == 2) /// 没有申请直播权限 /// 没有绑定微博
    {
        [self.view addSubview:self.btn1];
    }
}


#pragma mark - ********************** Functions **********************

#pragma mark - 注册消息

- (void)regNotification
{
    // 绑定成功消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess:) name:@"kBindSuccess" object:nil];
    // 绑定失败消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginFail:) name:@"kBindFail" object:nil];
    
    // 登录成功消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess:) name:@"kLoginSuccess" object:nil];
    // 登录失败消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginFail:) name:@"kLoginFail" object:nil];
}

#pragma mark - demo

- (void)showTipMessage:(NSString *)str
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [MPTTips showTips:str duration:1.0f];
    });
}


#pragma mark - ********************** Button Touch Event **********************

- (void)btnClickBack:(TPButton *)sender
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)btnClickShenqing:(TPButton *)sender
{
    NSNumber *number = [[NSUserDefaults standardUserDefaults] objectForKey:LiveCode];
    
    if(number.integerValue == 2)
    {
        [JLRoutes routeURL:[NSURL URLWithString:@"/login/sso/sina"]];
    }
    else if (number.integerValue == 3)
    {
        [self req_ApplyLive];
    }
}

- (void)btnClickShenqingOther:(TPButton *)sender
{
    [MPTLoginApp logout];
    [JLRoutes routeURL:[NSURL URLWithString:@"/login/sso/sina"]];
}


#pragma mark - ********************** Net Connection Event **********************

/**
 *  申请白名单资格
 */
- (void)req_ApplyLive
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSString *weiboToken = @"";
    if([MPTLoginUser unArchiver].sinaPaike.weiboId != nil)
    {
        weiboToken = [MPTLoginUser unArchiver].sinaPaike.weiboToken;
    }
    NSDictionary *paraDic = @{
                              @"weiboToken":[MPTSingleObjectInstance setStrDefValue:weiboToken]
                              };
    
    [[MPTHttpClient sharedMPHTTPClient] getPath:@"m/applyLive.json" parameters:paraDic
                                  queuePriority:NSOperationQueuePriorityNormal
                                   cacheRequest:NO
                                        success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         [MBProgressHUD hideHUDForView:self.view animated:YES];
         
         /// 保存直播状态
         [[NSUserDefaults standardUserDefaults] setValue:responseObject[@"code"] forKey:LiveCode];
         
         if([responseObject[@"code"] integerValue] == 1)
         {
           
             
             // 白名单
             [self dismissViewControllerAnimated:YES completion:^{
                 
             }];
             if ([[TPTabBarManager share] getLastIndex] == 0)
             {
                 [[NSNotificationCenter defaultCenter] postNotificationName:@"HomeLive" object:nil];
             }
             else
             {
                 [[NSNotificationCenter defaultCenter] postNotificationName:@"MeLive" object:nil];
             }
         }
         
         [UIView animateWithDuration:0.5 animations:^{
             self.btn1.alpha = 0.0f;
         } completion:^(BOOL finished) {
             [self.btn1 removeFromSuperview];
         }];
         
         self.btn2.alpha = 0.0f;
         [self.view addSubview:self.btn2];
         [UIView animateWithDuration:0.5 animations:^{
             self.btn2.alpha = 1.0f;
         } completion:^(BOOL finished) {
             self.btn2.alpha = 1.0f;
         }];
     }
     failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [MBProgressHUD hideHUDForView:self.view animated:YES];
         [self performSelector:@selector(showTipMessage:) withObject:@"服务器开小差了" afterDelay:1.0f];
     }
     cached:^(NSDictionary *cachedObject)
     {
         
     }];
}

- (void)req_Authory
{
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSDictionary *paraDic = @{@"version":ZB_Str_Protect(version),
                              @"unique_id":ZB_Str_Protect([NSString MPTIdentifierString])
                              };
    
    [[MPTHttpClient sharedMPHTTPClient] getPath:@"m/checkLiveAuth.json" parameters:paraDic queuePriority:NSOperationQueuePriorityNormal cacheRequest:NO success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         if ([responseObject isKindOfClass:[NSDictionary class]])
         {
             if ([responseObject[@"status"] integerValue] == 200)
             {
                 /// 保存直播状态
                 [[NSUserDefaults standardUserDefaults] setValue:responseObject[@"code"] forKey:LiveCode];
                 
                 
                 if([responseObject[@"code"] integerValue] == 1)
                 {
                     // 白名单
                     [self dismissViewControllerAnimated:YES completion:^{
                         
                         if ([[TPTabBarManager share] getLastIndex] == 0)
                         {
                             [[NSNotificationCenter defaultCenter] postNotificationName:@"HomeLive" object:nil];
                         }
                         else
                         {
                             [[NSNotificationCenter defaultCenter] postNotificationName:@"MeLive" object:nil];
                         }
                         
                     }];
                 }
                 
                 if([responseObject[@"code"] integerValue] == 2)
                 {
                     // 未绑定微博
                     
                 }
                 
                 if([responseObject[@"code"] integerValue] == 3 &&
                    [responseObject[@"code"] integerValue] != 4)
                 {
                     // 没在白名单中
                     [self req_ApplyLive];
                 }
                 
                 if([responseObject[@"code"] integerValue] == 4)
                 {
                     // 审核中
                     [UIView animateWithDuration:0.5 animations:^{
                         self.btn1.alpha = 0.0f;
                     } completion:^(BOOL finished) {
                         [self.btn1 removeFromSuperview];
                     }];
                     
                     self.btn2.alpha = 0.0f;
                     [self.view addSubview:self.btn2];
                     [UIView animateWithDuration:0.5 animations:^{
                         self.btn2.alpha = 1.0f;
                     } completion:^(BOOL finished) {
                         self.btn2.alpha = 1.0f;
                     }];
                 }
             }
         }
     }
                                        failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         
     }
                                         cached:^(NSDictionary *cachedObject)
     {
         
     }];
}

#pragma mark - ********************** Delegate Event **********************

#pragma mark - 代理 xxx



#pragma mark - ********************** Notification Event **********************

/// 登录成功
- (void)loginSuccess:(NSNotification *)note
{
    [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:YES];
    
    /// 请求直播状态接口
    [self req_Authory];
}

///登录失败了
- (void)loginFail:(NSNotification *)notification
{
    [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:YES];
    [MPTTips showSingleTips:@"用户登录失败，请重新登录" duration:1.5];
}


@end
